<template>
  <div>
    <div class="dashboard-header">
      <h2>商家仪表盘</h2>
      <div class="period-selector">
        <el-radio-group v-model="period" size="small">
          <el-radio-button label="today">今天</el-radio-button>
          <el-radio-button label="week">本周</el-radio-button>
          <el-radio-button label="month">本月</el-radio-button>
        </el-radio-group>
      </div>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stat-cards">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-card-content">
          <div class="stat-icon sales-icon">
            <i class="el-icon-shopping-cart-full"></i>
          </div>
          <div class="stat-details">
            <h3 class="stat-title">总销售额</h3>
            <p class="stat-value">¥5,240.50</p>
            <p class="stat-change increase">较上期增长15%</p>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <div class="stat-card-content">
          <div class="stat-icon orders-icon">
            <i class="el-icon-s-order"></i>
          </div>
          <div class="stat-details">
            <h3 class="stat-title">订单数</h3>
            <p class="stat-value">124</p>
            <p class="stat-change increase">较上期增长8%</p>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <div class="stat-card-content">
          <div class="stat-icon customers-icon">
            <i class="el-icon-user"></i>
          </div>
          <div class="stat-details">
            <h3 class="stat-title">新增客户</h3>
            <p class="stat-value">45</p>
            <p class="stat-change increase">较上期增长12%</p>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <div class="stat-card-content">
          <div class="stat-icon products-icon">
            <i class="el-icon-goods"></i>
          </div>
          <div class="stat-details">
            <h3 class="stat-title">售出商品</h3>
            <p class="stat-value">286</p>
            <p class="stat-change decrease">较上期下降3%</p>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 最近订单和库存提醒 -->
    <div class="dashboard-grid">
      <el-card class="recent-orders" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>最近订单</span>
            <el-button type="text" @click="$router.push('/merchant/orders')">查看全部</el-button>
          </div>
        </template>
        <el-table :data="recentOrders" style="width: 100%" :show-header="false">
          <el-table-column width="60">
            <template #default>
              <div class="order-icon">
                <i class="el-icon-shopping-bag-1"></i>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="customer" label="Customer">
            <template #default="scope">
              <div class="order-info">
                <p class="order-id">{{ scope.row.id }}</p>
                <p class="order-customer">{{ scope.row.customer }}</p>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="Amount" width="100" align="right">
            <template #default="scope">
              <span class="order-amount">{{ scope.row.amount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="Status" width="120" align="right">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)" size="small">{{ getChineseStatus(scope.row.status) }}</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <el-card class="inventory-alerts" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>库存预警</span>
            <el-button type="text" @click="$router.push('/merchant/inventory')">查看全部</el-button>
          </div>
        </template>
        <div v-if="lowStockItems.length === 0" class="empty-state">
          <i class="el-icon-check"></i>
          <p>当前没有库存预警</p>
        </div>
        <ul v-else class="alert-list">
          <li v-for="item in lowStockItems" :key="item.id" class="alert-item">
            <div class="alert-icon warning">
              <i class="el-icon-warning-outline"></i>
            </div>
            <div class="alert-content">
              <p class="alert-title">{{ item.name }}库存不足</p>
              <p class="alert-message">仅剩{{ item.quantity }}件</p>
            </div>
            <el-button size="mini" type="warning">补货</el-button>
          </li>
        </ul>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import productApi from '../../api/product';

// 当前时间段
const period = ref('month');

// 订单数据
const allOrders = ref([
  { id: 'ORD-1001', date: '2023-08-10', customer: '张三', amount: '¥125.00', status: 'Delivered' },
  { id: 'ORD-1002', date: '2023-08-11', customer: '李四', amount: '¥89.50', status: 'Processing' },
  { id: 'ORD-1003', date: '2023-08-12', customer: '王五', amount: '¥210.75', status: 'Shipped' },
  { id: 'ORD-1004', date: '2023-08-13', customer: '赵六', amount: '¥150.20', status: 'Pending' },
  { id: 'ORD-1005', date: '2023-08-14', customer: '钱七', amount: '¥75.99', status: 'Cancelled' }
]);

// 商品数据
const products = ref([]);
const loading = ref(false);

// 获取最近订单
const recentOrders = computed(() => allOrders.value.slice(0, 4));

// 库存预警相关逻辑
const lowStockItems = computed(() => {
  // 过滤库存低的商品
  return products.value
    ? products.value
        .filter(product => (product.stock || 0) < 10)
        .map(product => ({
          id: product.id,
          name: product.name,
          quantity: product.stock || 0
        }))
    : [];
});

// 获取商品列表
const fetchProducts = async () => {
  loading.value = true;
  
  try {
    console.log('开始获取商品列表数据');
    
    // 使用商品API服务
    const result = await productApi.getProductsPage({
      page: 0,
      size: 100,
      sort: 'id',
      direction: 'desc'
    });
    
    console.log('API响应数据:', result);
    
    const data = result.data;
    products.value = data.content;
    console.log('处理后的商品数据:', products.value);
  } catch (error) {
    console.error('获取商品列表出错:', error);
    ElMessage.error(`网络错误: ${error.message || '未知错误'}`);
    // 如果API请求出错，使用模拟数据作为备用
    products.value = [
      {
        id: 'P001',
        name: '奢华滋养面霜',
        sku: 'SKU001',
        price: 299.00,
        stock: 5,
        sales: 128
      },
      {
        id: 'P002',
        name: '清透防晒乳',
        sku: 'SKU002',
        price: 159.00,
        stock: 8,
        sales: 89
      }
    ];
  } finally {
    loading.value = false;
  }
};

// 状态转换方法
const getStatusType = (status) => {
  const statusMap = {
    'Delivered': 'success',
    'Processing': 'warning',
    'Shipped': 'info',
    'Pending': 'primary',
    'Cancelled': 'danger'
  };
  return statusMap[status] || 'info';
};

const getChineseStatus = (status) => {
  const statusMap = {
    'Delivered': '已送达',
    'Processing': '处理中',
    'Shipped': '已发货',
    'Pending': '待处理',
    'Cancelled': '已取消'
  };
  return statusMap[status] || status;
};

onMounted(() => {
  // 获取商品列表
  fetchProducts();
});
</script>

<style scoped>
.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.dashboard-header h2 {
  margin: 0;
  color: #303133;
  font-weight: bold;
  position: relative;
  padding-bottom: 8px;
}

.dashboard-header h2:after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 0;
  width: 40px;
  height: 3px;
  background-color: #67C23A;
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 25px;
}

.stat-card {
  border-radius: 8px;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-card-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 64px;
  height: 64px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 32px;
  color: white;
}

.sales-icon {
  background-color: #409EFF;
}

.orders-icon {
  background-color: #67C23A;
}

.customers-icon {
  background-color: #E6A23C;
}

.products-icon {
  background-color: #F56C6C;
}

.stat-title {
  font-size: 14px;
  color: #606266;
  margin: 0 0 5px 0;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin: 0 0 5px 0;
  color: #303133;
}

.stat-change {
  font-size: 12px;
  margin: 0;
}

.increase {
  color: #67C23A;
}

.decrease {
  color: #F56C6C;
}

.dashboard-grid {
  display: grid;
  grid-template-columns: 3fr 2fr;
  gap: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.order-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #409EFF;
}

.order-info {
  display: flex;
  flex-direction: column;
}

.order-id {
  margin: 0;
  font-weight: bold;
  color: #303133;
}

.order-customer {
  margin: 0;
  font-size: 12px;
  color: #606266;
}

.order-amount {
  font-weight: bold;
  color: #303133;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.empty-state i {
  font-size: 32px;
  color: #67C23A;
  margin-bottom: 10px;
}

.alert-list {
  padding: 0;
  margin: 0;
  list-style: none;
}

.alert-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #EBEEF5;
}

.alert-item:last-child {
  border-bottom: none;
}

.alert-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  color: white;
}

.warning {
  background-color: #E6A23C;
}

.alert-content {
  flex: 1;
}

.alert-title {
  margin: 0;
  font-weight: bold;
  color: #303133;
}

.alert-message {
  margin: 5px 0 0 0;
  font-size: 12px;
  color: #606266;
}

@media (max-width: 1200px) {
  .stat-cards {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .dashboard-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .filter-bar {
    flex-direction: column;
  }
}
</style> 